/*
 * Copyright (C) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import Ability from '@ohos.app.ability.UIAbility'
import BundleManager from '../common/utils/BundleMangerUtils';
import display from '@ohos.display' // 导入模块
import WorkerHandler from '../common/profiler/WorkerHandler';
import worker from '@ohos.worker';
import { initDb } from '../common/database/LocalRepository'
import { FloatWindowFun } from '../common/ui/floatwindow/FloatWindowFun'
import deviceInfo from '@ohos.deviceInfo'
import  abilityAccessCtrl from '@ohos.abilityAccessCtrl'
import fileShare from '@ohos.fileshare';
let MainWorker = new worker.ThreadWorker("/entry/ets/workers/worker.js")
globalThis.MainWorker = MainWorker

MainWorker.onmessage = function (result) {
    WorkerHandler.socketHandler(result)
}

let abilityWindowStage;
export default class MainAbility extends Ability {

    // async onCreate(want, launchParam) {
    //     globalThis.showFloatingWindow=false
    //     globalThis.abilityContext = this.context
    //     let atManager = abilityAccessCtrl.createAtManager()
    //     try {
    //         await atManager.requestPermissionsFromUser(globalThis.abilityContext, ['ohos.permission.GET_INSTALLED_BUNDLE_LIST']).then(data => {
    //             BundleManager.getAppList().then(appList => {
    //                 globalThis.appList = appList
    //             })
    //         }).catch(err=>{
    //             console.log('permission data:' +JSON.stringify(err))
    //         })
    //     } catch (err){
    //         console.log('permission catch err:' +JSON.stringify(err))
    //     }
    //     globalThis.isNeedLogin = true
    //     globalThis.curUserLogin = 'test'
    // }
    onCreate(want, launchParam) {
        globalThis.showFloatingWindow=false
        BundleManager.getAppList().then(appList => {
            globalThis.appList = appList
        })
        const that = this
        this.context.eventHub.on("getAbilityData", (data) => {
            data.context = that.context
            data.launchWant = want
        })
        this.requestPermission()
        AppStorage.SetOrCreate('context', this.context)
    }
    requestPermission = async () => {
        let permissionRequestResult = await abilityAccessCtrl.createAtManager().requestPermissionsFromUser(this.context,
            [
                'ohos.permission.SYSTEM_FLOAT_WINDOW',
            ]);
        // 如果权限列表中有-1，说明用户拒绝了授权
        if (permissionRequestResult.authResults[0] === 0) {


            console.info('MainAbility permissionRequestResult success')
        }
    }
    onDestroy() {
        MainWorker.terminate()
    }
    onWindowStageCreate(windowStage) {
        globalThis.abilityContext = this.context
        console.log(deviceInfo.productModel)
        console.log(deviceInfo.deviceType)

        abilityWindowStage = windowStage;
        let windowClass = null
        windowStage.getMainWindow((err, data) => {
            windowClass = data
            if (deviceInfo.deviceType.toString() != 'tablet')  {
                let isLayoutFullScreen = true
                windowClass.setWindowLayoutFullScreen(isLayoutFullScreen, err => {
                    if (err.code) {
                        return
                    }
                })
                let sysBarProps = {
                    statusBarColor: '#00000000',
                    navigationBarColor: '#00ff00',
                    statusBarContentColor: '#ffffff',
                    navigationBarContentColor: '#ffffff'
                }
                windowClass.setWindowSystemBarProperties(sysBarProps, err => {
                    if (err.code) {
                        return
                    }
                })
            }
        })

        abilityWindowStage.setUIContent(this.context, "pages/MainPage", null)
        globalThis.useDaemon = false
        let disp = display.getDefaultDisplaySync()
        globalThis.screenWith = disp.width
        if(globalThis.screenWith>1400){
            globalThis.coefficient=1
        }else if( globalThis.screenWith>800&&globalThis.screenWith<1400){
            globalThis.coefficient=1.8
        }else{
            globalThis.coefficient=1
        }
    }
    onForeground() {
        initDb()
        FloatWindowFun.initAllFun()
        //NetWork.getInstance().init()
        MainWorker.postMessage({ "testConnection": true })
    }
};





